<template>
	<view style="margin-top: 300px;">
		<textarea v-model="text" style="border: 1px solid red;width: 100%;height: 400px;" :maxlength="-1"
			placeholder-style="color:#F76260" placeholder="请输入要合成语音的内容"></textarea>
		<view style="font-size: 28px; text-align: center; margin-top: 20px;" @tap="start">开始合成</view>
	</view>
</template>
<style>
	textarea {
		border: 1px solid red;
		width: 100%;
		height: 400px;
	}

	view {
		font-size: 28px;
		text-align: center;
		margin-top: 20px;
	}
</style>
<script>
	import TextToSpeech from './textToSpeech';

	export default {
		name: 'VoiceSynthesis',
		components: {},
		props: {},
		data() {
			return {
				text: 'my name is zhangtr',
				response: '',
				speech: null,
				mediaSource: null,
				sourceBuffer: null,
				audioElement: null
			};
		},
		computed: {},
		watch: {},
		mounted() {
			if (!('MediaSource' in window) || !MediaSource.isTypeSupported('audio/mpeg')) {
				console.error('MediaSource or the specified MIME type is not supported in this environment.');
				return;
			}

			this.speech = TextToSpeech({
				SecretKey: 'V2X3d8ulhirvtkVFtPygTJa0Nl6bCHVe',
				SecretId: 'AKIDDYp3Nf0FR4vpeNzW9gK1oYSMCHONMKNB',
				AppId: 1323065199,
				url: 'tts.cloud.tencent.com/stream_ws'
			});

			uni.onSocketOpen(() => {
				console.log('WebSocket连接已打开！');
				this.setupAudio();
			});

			uni.onSocketError((res) => {
				console.error('WebSocket连接打开失败，请检查！', res);
			});

			uni.onSocketMessage((res) => {
				console.log('收到服务器内容', res.data);
				if (typeof res.data === 'string') {
					const data = JSON.parse(res.data);
					if (data.final === 1) {
						console.log('语音合成完成');
						if (this.sourceBuffer) {
							this.sourceBuffer.endOfStream();
						}
					}
				} else {
					this.appendBuffer(res.data);
				}
			});

			uni.onSocketClose(() => {
				console.log('WebSocket 已关闭！');
				if (this.sourceBuffer) {
					this.sourceBuffer.endOfStream();
				}
			});
		},
		methods: {
			setupAudio() {
				this.mediaSource = new MediaSource();
				this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen.bind(this));
				this.audioElement = document.getElementById('audioPlayer');
				this.audioElement.src = URL.createObjectURL(this.mediaSource);
			},
			handleSourceOpen() {
				console.log('MediaSource opened.');
				const mimeType = 'audio/mpeg';
				if (!MediaSource.isTypeSupported(mimeType)) {
					console.error('MIME type not supported:', mimeType);
					return;
				}
				try {
					this.sourceBuffer = this.mediaSource.addSourceBuffer(mimeType);
					console.log('SourceBuffer created successfully.');
					this.sourceBuffer.addEventListener('updateend', () => {
						if (!this.sourceBuffer.updating && this.arrayBuffers.length > 0) {
							this.appendBuffer(this.arrayBuffers.shift());
						}
					});
					this.audioElement.play();
				} catch (error) {
					console.error('Failed to create SourceBuffer:', error);
				}
			},
			appendBuffer(data) {
				if (this.sourceBuffer && !this.sourceBuffer.updating) {
					try {
						this.sourceBuffer.appendBuffer(data);
						console.log('Data appended successfully.');
					} catch (error) {
						console.error('Failed to append buffer:', error);
					}
				} else {
					console.warn('sourceBuffer is either null or updating.');
					if (!this.arrayBuffers) {
						this.arrayBuffers = [];
					}
					this.arrayBuffers.push(data);
				}
			},
			start() {
				if (!this.text.trim()) {
					uni.showToast({
						title: '请输入内容',
						icon: 'none'
					});
					return;
				}

				this.speech.start({
					Text: this.text
				});
			}
		}
	};
</script>